import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { Card, Row, Col, Button, Steps, message, Modal, Spin } from 'antd';
import { ShoppingCartOutlined, CheckCircleOutlined } from '@ant-design/icons';
import MovieService from '../services/MovieService';
import '../styles/SeatSelection.css';

const { Step } = Steps;

const SeatSelection = () => {
  const { screeningId } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedSeats, setSelectedSeats] = useState([]);
  const [seats, setSeats] = useState([]);
  const [screening, setScreening] = useState(null);
  const [movie, setMovie] = useState(null);
  const [totalPrice, setTotalPrice] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchScreeningData = async () => {
      try {
        setLoading(true);
        // 从location.state中获取电影和场次信息
        const passedScreening = location.state?.screening;
        const passedMovie = location.state?.movie;
        
        if (passedScreening && passedMovie) {
          // 使用传递过来的数据
          setScreening({
            id: passedScreening.id,
            movie: {
              title: passedMovie.title,
              duration: `${passedMovie.durationMinutes}分钟`,
              type: passedMovie.categories?.join('/')
            },
            cinema: {
              name: passedScreening.cinemaName,
              hall: passedScreening.hallName
            },
            time: passedScreening.startTime,
            price: passedScreening.price
          });
          setMovie(passedMovie);
        } else {
          // 如果没有传递数据，则模拟获取场次信息
          const mockScreening = {
            id: screeningId,
            movie: {
              title: '流浪地球2',
              duration: '173分钟',
              type: '科幻/冒险'
            },
            cinema: {
              name: '万达影城（XX店）',
              hall: '1号厅'
            },
            time: '2024-03-06 14:30',
            price: 45.00
          };
          setScreening(mockScreening);
        }

        // 使用MovieService获取座位数据
        const seatsResponse = await MovieService.getSeats(screeningId);
        setSeats(seatsResponse.data);
        
        setLoading(false);
      } catch (error) {
        console.error('Error fetching screening data:', error);
        message.error('获取场次数据失败，请重试');
        setLoading(false);
      }
    };

    fetchScreeningData();
  }, [screeningId, location.state]);

  const handleSeatClick = (seat) => {
    if (seat.status === 'occupied') {
      message.warning('该座位已被选择');
      return;
    }

    const newSelectedSeats = [...selectedSeats];
    const index = newSelectedSeats.findIndex(s => s.id === seat.id);

    if (index === -1) {
      if (newSelectedSeats.length >= 5) {
        message.warning('最多只能选择5个座位');
        return;
      }
      newSelectedSeats.push(seat);
    } else {
      newSelectedSeats.splice(index, 1);
    }

    setSelectedSeats(newSelectedSeats);
    setTotalPrice(newSelectedSeats.length * screening.price);
  };

  const handleConfirm = () => {
    if (selectedSeats.length === 0) {
      message.warning('请选择座位');
      return;
    }

    // Navigate to order confirmation page with order details
    navigate('/order/confirm', { 
      state: { 
        screeningId: screeningId,
        order: {
          id: 'ORD' + Math.floor(Math.random() * 1000000),
          movie: screening.movie.title,
          cinema: screening.cinema.name,
          hall: screening.cinema.hall,
          date: screening.time.split(' ')[0],
          time: screening.time.split(' ')[1],
          seats: selectedSeats.map(seat => `${seat.row}排${seat.col}座`),
          ticketPrice: screening.price,
          serviceCharge: 5,
          totalAmount: (selectedSeats.length * screening.price) + 5
        }
      }
    });
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!screening) {
    return <div>场次信息不存在或已过期</div>;
  }

  return (
    <div className="seat-selection">
      <Steps current={0} className="steps">
        <Step title="选择座位" />
        <Step title="确认订单" />
        <Step title="支付" />
        <Step title="完成" />
      </Steps>

      <Row gutter={24}>
        <Col span={18}>
          <Card className="seat-map">
            <div className="screen">银幕</div>
            <div className="seats-container">
              {seats.map((row, rowIndex) => (
                <div key={rowIndex} className="seat-row">
                  {row.map(seat => (
                    <div
                      key={seat.id}
                      className={`seat ${seat.status} ${selectedSeats.some(s => s.id === seat.id) ? 'selected' : ''}`}
                      onClick={() => handleSeatClick(seat)}
                    >
                      {seat.row}排{seat.col}座
                    </div>
                  ))}
                </div>
              ))}
            </div>
            <div className="seat-legend">
              <div className="legend-item">
                <div className="seat available"></div>
                <span>可选</span>
              </div>
              <div className="legend-item">
                <div className="seat occupied"></div>
                <span>已选</span>
              </div>
              <div className="legend-item">
                <div className="seat selected"></div>
                <span>选中</span>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card className="order-info">
            <h3>{screening.movie.title}</h3>
            <div className="info-item">
              <span className="label">影院：</span>
              <span>{screening.cinema.name}</span>
            </div>
            <div className="info-item">
              <span className="label">影厅：</span>
              <span>{screening.cinema.hall}</span>
            </div>
            <div className="info-item">
              <span className="label">时间：</span>
              <span>{screening.time}</span>
            </div>
            <div className="info-item">
              <span className="label">座位：</span>
              <span>
                {selectedSeats.length > 0
                  ? selectedSeats.map(seat => `${seat.row}排${seat.col}座`).join('、')
                  : '未选择'}
              </span>
            </div>
            <div className="info-item price">
              <span className="label">总价：</span>
              <span className="value">¥{totalPrice}</span>
            </div>
            <Button
              type="primary"
              size="large"
              icon={<ShoppingCartOutlined />}
              onClick={handleConfirm}
              disabled={selectedSeats.length === 0}
            >
              确认选座
            </Button>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default SeatSelection; 